package com.ec.system.modules.sys.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ec.core.common.constants.TenantConstant;
import com.ec.core.common.core.base.BasePageVO;
import com.ec.core.common.enums.GlobalResponseResultEnum;
import com.ec.core.common.exception.BizException;
import com.ec.core.common.utils.BeanUtilEx;
import com.ec.core.mybatis.entity.TenantEntity;
import com.ec.core.mybatis.utils.CorePageUtil;
import com.ec.core.secure.utils.SecureUtil;
import com.ec.system.modules.sys.dto.QueryRoleDTO;
import com.ec.system.modules.sys.dto.SysRoleDTO;
import com.ec.system.modules.sys.entity.SysRole;
import com.ec.system.modules.sys.entity.SysRoleMenu;
import com.ec.system.modules.sys.mapper.SysRoleMapper;
import com.ec.system.modules.sys.service.ISysRoleMenuService;
import com.ec.system.modules.sys.service.ISysRoleService;
import com.ec.system.modules.sys.vo.SysRoleVO;
import com.google.common.collect.Maps;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @description:
 * @author: Eric Lee
 * @time: 2021/8/6 17:51
 */
@Service
public class SysRoleServiceImpl extends ServiceImpl<SysRoleMapper, SysRole> implements ISysRoleService {
    @Resource
    private ISysRoleMenuService sysRoleMenuService;

    @Override
    public List<SysRole> queryRoleByUserId(Long userId) {
        return baseMapper.queryRoleByUserId(userId);
    }

    @Override
    public BasePageVO<SysRoleVO> listRole(QueryRoleDTO queryRoleDTO) {
        LambdaQueryWrapper<SysRole> wrapper = Wrappers.lambdaQuery();
        if (Objects.isNull(queryRoleDTO.getTenantId())) {
            wrapper.eq(TenantEntity::getTenantId, SecureUtil.userTenantId());
        } else {
            wrapper.eq(TenantEntity::getTenantId, queryRoleDTO.getTenantId());
        }
        if (StringUtils.isNotBlank(queryRoleDTO.getRoleName())) {
            wrapper.like(SysRole::getRoleName, queryRoleDTO.getRoleName());
        }
        if (StringUtils.isNotBlank(queryRoleDTO.getRoleCode())) {
            wrapper.eq(SysRole::getRoleCode, queryRoleDTO.getRoleCode());
        }
        IPage<SysRole> page = page(new Page<>(queryRoleDTO.getPageNo(), queryRoleDTO.getPageSize()), wrapper);
        return CorePageUtil.buildPageResult(page, SysRoleVO.class);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean addRole(SysRoleDTO sysRoleDTO) {
        SysRole SysRole = new SysRole();
        sysRoleDTO.setRoleCode(sysRoleDTO.getRoleCode().toUpperCase());
        if (sysRoleDTO.getRoleCode().equals(TenantConstant.TENANT_ADMINISTRATOR)) {
            throw new BizException(GlobalResponseResultEnum.HANDEL_FAIL.getCode(), "角色编码不被允许！！！");
        }
        BeanUtilEx.copyProperties(sysRoleDTO, SysRole);
        SysRole.setTenantId(SecureUtil.userTenantId());
        return this.save(SysRole);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateRole(SysRoleDTO sysRoleDTO) {
        SysRole SysRole = new SysRole();
        BeanUtilEx.copyProperties(sysRoleDTO, SysRole, "roleCode");
        UpdateWrapper<SysRole> updateWrapper = Wrappers.update();
        updateWrapper.eq("role_id", sysRoleDTO.getRoleId());
        updateWrapper.eq("tenant_id", SecureUtil.userTenantId());
        return this.update(SysRole, updateWrapper);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteRole(SysRoleDTO sysRoleDTO) {
        SysRole sysRole = new SysRole();
        BeanUtil.copyProperties(sysRoleDTO, sysRole);
        return removeById(sysRole);
//        LambdaUpdateWrapper<SysRole> updateWrapper = Wrappers.<SysRole>lambdaUpdate()
//                .set(SysRole::getIsDelete, CommonConstant.ALREADY_DELETED)
//                .eq(SysRole::getTenantId, SecureUtil.userTenantId())
//                .eq(SysRole::getRoleId, sysRoleDTO.getRoleId())
//                .notIn(SysRole::getRoleCode, Arrays.asList(TenantConstant.SUPER_ADMINISTRATOR, TenantConstant.TENANT_ADMINISTRATOR));
//        return this.update(updateWrapper);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean configRolePer(SysRoleDTO sysRoleDTO) {
        return saveRoleMenu(sysRoleDTO.getMenuIds(), sysRoleDTO.getRoleId());
    }

    /**
     * 保存角色菜单关联数据
     *
     * @param menuIds 菜单id，逗号分割的字符串
     * @param roleId  角色id
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean saveRoleMenu(String menuIds, Long roleId) {
        // 先删除role对应的数据，在重新添加
        Map<String, Object> wrap = Maps.newHashMap();
        wrap.put("role_id", roleId);
        sysRoleMenuService.removeByMap(wrap);
        List<Long> menuIdList = Arrays.stream(menuIds.split(",")).mapToLong(Long::parseLong).boxed().collect(Collectors.toList());
        List<SysRoleMenu> collect = menuIdList.stream().map(e -> {
            SysRoleMenu SysRoleMenu = new SysRoleMenu();
            SysRoleMenu.setMenuId(e);
            SysRoleMenu.setRoleId(roleId);
            return SysRoleMenu;
        }).collect(Collectors.toList());
        sysRoleMenuService.saveBatch(collect);
        return true;
    }
}
